﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace RhythmComet.Services
{
    public interface IInputHandler 
    {
        GamePadState GamePadState { get; }

        GamePadState LastGamePadState { get; }

        bool WasPressed(Buttons button);

#if !XBOX
        KeyboardState KeyboardState { get; }

        KeyboardState LastKeyboardState { get; }

        bool WasPressed(Keys key);
#endif

    }

    public class InputHandler : GameComponent, IInputHandler
    {
        #region Fields and Properties
        Game game;

#if !XBOX
        private KeyboardState lastKeyboardState;
        private KeyboardState keyboardState;
#endif

        private GamePadState lastGamepadState;
        private GamePadState gamepadState;

        public GamePadState GamePadState
        {
            get { return gamepadState; }
        }

        public GamePadState LastGamePadState
        {
            get { return lastGamepadState; }
        }

#if !XBOX
        public KeyboardState KeyboardState
        {
            get { return keyboardState; }
        }

        public KeyboardState LastKeyboardState
        {
            get { return lastKeyboardState; }
        }
#endif
        
        #endregion

        public InputHandler(Game game)
            : base(game)
        {
            this.game = game;
            this.game.Services.AddService(typeof(IInputHandler), this);
        }

        public override void Initialize()
        {
#if !XBOX
            keyboardState = Keyboard.GetState();
#endif
            gamepadState = GamePad.GetState(PlayerIndex.One);

            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {

#if !XBOX
            lastKeyboardState = keyboardState;
#endif
            lastGamepadState = gamepadState;

#if !XBOX
            keyboardState = Keyboard.GetState();
#endif
            gamepadState = GamePad.GetState(PlayerIndex.One);

            base.Update(gameTime);
        }

#if !XBOX
        public bool WasPressed(Keys key)
        {
            if (KeyboardState.IsKeyDown(key) && LastKeyboardState.IsKeyUp(key))
            {
                return true;
            }
            return false;
        }
#endif

        public bool WasPressed(Buttons button)
        {
            if (GamePadState.IsButtonDown(button) && LastGamePadState.IsButtonUp(button))
            {
                return true;
            }
            return false;
        }
    }
}
